package com.qxzh.common.utils.uuid;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.qxzh.common.utils.spring.SpringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * ID生成器工具类
 *
 * @author ruoyi
 */
public class IdUtils {
    private static final StringRedisTemplate stringRedisTemplate = SpringUtils.getBean(StringRedisTemplate.class);

    /**
     * 获取随机UUID
     *
     * @return 随机UUID
     */
    public static String randomUUID() {
        return UUID.randomUUID().toString();
    }

    /**
     * 简化的UUID，去掉了横线
     *
     * @return 简化的UUID，去掉了横线
     */
    public static String simpleUUID() {
        return UUID.randomUUID().toString(true);
    }

    /**
     * 获取随机UUID，使用性能更好的ThreadLocalRandom生成UUID
     *
     * @return 随机UUID
     */
    public static String fastUUID() {
        return UUID.fastUUID().toString();
    }

    /**
     * 简化的UUID，去掉了横线，使用性能更好的ThreadLocalRandom生成UUID
     *
     * @return 简化的UUID，去掉了横线
     */
    public static String fastSimpleUUID() {
        return UUID.fastUUID().toString(true);
    }

    public static String getShortNo(String prefix) {
        long workId = RandomUtil.randomLong(0, 32); // (0, 31];
        long dataId = RandomUtil.randomLong(0, 32); // (0, 31];
        long id = IdUtil.getSnowflake(workId, dataId).nextId();//得到id 很长且高位很长部分是一样的数
        StringBuilder sb = new StringBuilder(id + "");
        StringBuilder reverse = sb.reverse();//将id翻转：我们发现id很长，且高位很长部分是一样的数
        id = new Long(reverse.toString()) / 1000;//切去部分长度
        while (id > 1999999999) {//1999999999以内的10位或9位或8位id;....
            id /= 10;
        }
        String userNo = String.valueOf(id);
        String genUserNoKey = "getShortNo";
        if (StrUtil.isBlank(prefix)) {
            genUserNoKey = genUserNoKey + ":" + prefix;
        }
        Boolean member = stringRedisTemplate.opsForSet().isMember(genUserNoKey, userNo);
        if (Boolean.TRUE.equals(member)) {
            return getShortNo(); // 如果存在userNo，继续生成
        }
        stringRedisTemplate.opsForSet().add(genUserNoKey, userNo);
        return userNo;
    }

    public static String getShortNo() {
        return getShortNo(null);
    }
}
